﻿using System;
using DAL.Repositories;
using GameAdmin.Classes;

namespace GameAdmin.Pages
{
    public partial class user : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            btnSave.Click += new EventHandler(btnSave_Click);
            btnChangePassword.Click += new EventHandler(btnChangePassword_Click);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty((string)RouteData.Values["loginName"])) return;

            if (!IsPostBack)
            {
                LoadUserDetails();
            }
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    DAL.POCO.User u = new DAL.POCO.User();
                    u.login = txtLogin.Text;
                    u.jmeno = txtName.Text;
                    u.prijmeni = txtLastname.Text;
                    u.email = txtEmail.Text;
                    u.admin = chkBoxAdmin.Checked;

                    UserRepository.Update(u);

                    Response.Redirect("~/users", true);
                }
                catch (Exception ex)
                {
                    lblMessage.Text = ex.Message;
                    lblMessage.Visible = true;
                }
            }
        }

        void btnChangePassword_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblMessage.Visible = true;

                try
                {
                    string newPassword = Security.CreateHash(txtNewPassword.Text);
                    UserRepository.UpdatePassword(txtLogin.Text, newPassword);

                    lblMessage.Text = "Heslo bolo úspešne zmenené.";
                    txtNewPassword.Text = "";
                }
                catch (Exception ex)
                {
                    lblMessage.Text = ex.Message;
                }
            }
        }

        private void LoadUserDetails()
        {
            DAL.POCO.User u = UserRepository.GetUser((string)RouteData.Values["loginName"]);

            literalUserLogin.Text = u.login;
            
            txtLogin.Text = u.login;
            txtName.Text = u.jmeno;
            txtLastname.Text = u.prijmeni;
            txtEmail.Text = u.email;
            chkBoxAdmin.Checked = u.admin;
        }
    }
}